package com.itheima.reggie.srevice.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.srevice.DishService;
import com.itheima.reggie.srevice.SetmealDishService;
import com.itheima.reggie.srevice.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;

    /**
     * 新增套餐，添加菜品
     */
    @Override
    public void saveWithDish(SetmealDto setmealDto) {
        this.save(setmealDto);
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes.stream().map(item -> {
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());

        setmealDishService.saveBatch(setmealDishes);

    }

    /**
     * 批量删除，删除菜品
     *
     * @param ids
     */
    @Override
    public void removeWithDish(List<Long> ids) {
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Setmeal::getId, ids);
        //起售状态不能删除
        //queryWrapper.eq(Setmeal::getStatus, 1);
        int count = this.count(queryWrapper);
        //查询有结果，不能删除
        if (count > 0) {
            throw new CustomException("套餐正在售卖，不能删除");
        }
        //删除套餐里的菜品
        LambdaQueryWrapper<SetmealDish> dlw = new LambdaQueryWrapper<>();
        dlw.in(SetmealDish::getSetmealId,ids);

        setmealDishService.remove(dlw);
        //删除套餐
        this.removeByIds(ids);

    }

    @Override
    public void updateWithDish(SetmealDto setmealDto){
        //得到套餐id
        Long setmealId = setmealDto.getId();
        //通过套餐Id删除套餐下的所有菜品
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getSetmealId,setmealId);
        setmealDishService.remove(queryWrapper);

        //将新的菜品添加到套餐菜品中
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        //给每一个都添加上套餐Id
        setmealDishes.stream().map(item -> {
            item.setSetmealId(setmealId);
            return item;
        }).collect(Collectors.toList());
        setmealDishService.saveBatch(setmealDishes);

        //保存套餐
        this.updateById(setmealDto);

    }


}
